package com.twu.biblioteca;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.ArrayList;

/**
* Created by archoud on 3/5/14.
*/
public class UserIn {

    private final PrintStream stream;
    private BufferedReader bufferedReader;

    UserIn(PrintStream stream, BufferedReader bufferedReader){
        this.stream = stream;
        this.bufferedReader = bufferedReader;
    }



    public int getValidInputGivenRange(String promptType, int validRange) throws IOException {
        stream.printf("Enter your %s choice\n", promptType);

        String userChoice = bufferedReader.readLine();
        while(!isValidChoice(userChoice, validRange)) {
            stream.printf("Invalid %s option, try again\n", promptType);
            userChoice = bufferedReader.readLine();
        }

        return Integer.parseInt(userChoice) - 1;
    }

    private boolean isValidChoice(String choiceText, int validRange) {
        try {
            Integer choiceInt = Integer.parseInt(choiceText);

            return (choiceInt > 0 && choiceInt <= validRange);
        }
        catch (NumberFormatException e) {
            return false;
        }
    }
}
